package com.hand.wfive.util;

import android.media.MediaMetadataRetriever;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.Random;

public class FileUtils {

    private static final String TAG = FileUtils.class.getSimpleName();

    /**
     * 创建文件夹
     */
    public static String createFolder(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return file.mkdirs() ? "创建文件夹成功" : "创建文件夹失败";
        } else if (file.isFile()) {
            return file.mkdirs() ? "创建文件夹成功" : "创建文件夹失败";
        }
        return "文件夹已存在，无需创建";
    }

    /**
     * 创建文件
     */
    public static File createFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            logD("createFile(): ", "exists-delete=" + file.delete());
        }
        try {
            logD("createFile(): ", "create=" + file.createNewFile());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 创建Txt文件并写入内容
     */
    public static File createFile(String filePath, String content) {
        File file = createFile(filePath);
        try {
            FileOutputStream outStream = new FileOutputStream(file);
            outStream.write(content.getBytes());
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 删除文件夹(包含文件夹内容)
     */
    public static boolean deleteFolder(String folder) {
        // 如果dir不以文件分隔符结尾，自动添加文件分隔符
        if (!folder.endsWith(File.separator))
            folder = folder + File.separator;
        File dirFile = new File(folder);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            logD("deleteFolder(): ", "删除目录失败, ", folder, "不存在！");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        if (files != null && files.length > 0) {
            for (File file : files) {
                if (file.isFile()) {
                    // 删除子文件
                    flag = deleteFile(file.getAbsolutePath());
                    if (!flag) {
                        break;
                    }
                } else if (file.isDirectory()) {
                    // 删除子目录
                    flag = deleteFolder(file.getAbsolutePath());
                    if (!flag) {
                        break;
                    }
                }
            }
        }
        if (!flag) {
            return false;
        }
        // 删除当前目录
        return dirFile.delete();
    }

    /**
     * 删除文件
     */
    public static boolean deleteFile(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return true;
        }
        File file = new File(filePath);
        if (file.exists()) {
            return file.delete();
        }
        return true;
    }

    /**
     * 文件重命名
     */
    public static File renameFile(String oldPath, String newPath) {
        if (TextUtils.isEmpty(oldPath)) {
            return null;
        }
        if (TextUtils.isEmpty(newPath)) {
            return null;
        }
        File oldFile = new File(oldPath);
        File newFile = new File(newPath);
        boolean b = oldFile.renameTo(newFile);
        if (b) {
            return new File(newPath);
        }
        return null;
    }

    /**
     * 复制文件
     *
     * @param src  目标文件
     * @param dest 复制后的文件
     */
    public static boolean copyFile(File src, File dest) {
        if (src.getAbsolutePath().equals(dest.getAbsolutePath())) {
            return true;
        }
        try {
            InputStream in = new FileInputStream(src);
            FileOutputStream out = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) >= 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 复制文件
     *
     * @param oldPath 目标文件路径
     * @param newPath 复制后的文件路径
     */
    public static boolean copyFile(String oldPath, String newPath) {
        try {
            File oldFile = new File(oldPath);
            if (!oldFile.exists() || !oldFile.isFile() || !oldFile.canRead()) {
                return false;
            }
            // 读入原文件
            FileInputStream fileInputStream = new FileInputStream(oldPath);
            FileOutputStream fileOutputStream = new FileOutputStream(newPath);
            byte[] buffer = new byte[1024];
            int byteRead;
            while ((byteRead = fileInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            fileInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取文件大小 long
     */
    public static long getFileSize(String filePath) {
        if (TextUtils.isEmpty(filePath)) return 0;
        return getFileSize(new File(filePath));
    }

    /**
     * 获取文件大小 long
     */
    public static long getFileSize(File file) {
        long size = 0;
        try {
            if (file.exists()) {
                FileInputStream fis = new FileInputStream(file);
                size = fis.available();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 转换文件大小 String
     */
    public static String convertFileSize(long size) {
        DecimalFormat df = new DecimalFormat("#.00");
        String wrongSize = "0B";
        if (size == 0) {
            return wrongSize;
        }
        String fileSizeString;
        if (size < 1024) {
            fileSizeString = df.format((double) size) + "B";
        } else if (size < 1048576) {
            fileSizeString = df.format((double) size / 1024) + "KB";
        } else if (size < 1073741824) {
            fileSizeString = df.format((double) size / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) size / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 获取文件大小 String
     */
    public static String getFileSizeToS(File file) {
        return convertFileSize(getFileSize(file));
    }

    /**
     * 根据文件后缀名获得对应的MIME类型
     */
    public static String getMimeType(String filePath) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String mime = "*/*";
        if (filePath != null) {
            try {
                mmr.setDataSource(filePath);
                mime = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
            } catch (Exception e) {
                return mime;
            }
        }
        return mime;
    }

    /**
     * 随机生成文件名字，格式如：yyyyMMdd_12345
     *
     * @param pattern 传null或空时，默认yyyyMMdd
     */
    public static String getRandomFileName(String pattern) {
        if (TextUtils.isEmpty(pattern)) {
            pattern = "yyyyMMdd";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, Locale.CHINA);
        String str = simpleDateFormat.format(Calendar.getInstance().getTime());
        // 获取5位随机数
        Random random = new Random();
        int ranNum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
        return str + "_" + ranNum;
    }

    public static String getRandomFileName() {
        return getRandomFileName("yyyyMMdd_HHmmss");
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    public static byte[] readFileByBytes(String filePath) {
        try {
            File file = new File(filePath);
            ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
            short bufSize = 1024;
            byte[] buffer = new byte[bufSize];
            int len1;
            while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                bos.write(buffer, 0, len1);
            }
            return bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @return 获取文件后缀名, 包含 .
     */
    public static String getFileSuffix(String fileName) {
        if (TextUtils.isEmpty(fileName) || !fileName.contains(".")) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * @param fileName 带后缀的文件名
     * @return 不带后缀的文件名
     */
    public static String getFileNameNotSuffix(String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return "";
        }
        if (!fileName.contains(".")) {
            return fileName;
        }
        return fileName.substring(0, fileName.lastIndexOf("."));
    }

    private static void logD(String... msgs) {
        StringBuilder sb = new StringBuilder();
        if (msgs != null && msgs.length > 0) {
            for (String item : msgs) {
                sb.append(item);
            }
        }
        Log.d(TAG, sb.toString());
    }
}

